interface Dict {
  name: string;
  data: Array<Object>;
  update: number;
}

interface GetDictsParams {
  dictName: string;
  dictType?: "sys" | "biz";
}

/**
 * 字典系统
 * 自动缓存，根据过期时间配置自动更新，减少重复数据的请求
 */
const dicts = {
  namespaced: true,
  state: {
    // 过期时间
    expire: 10 * 60 * 1000,
    dictsMap:
      uni.getStorageSync("__APP__DICTS") ||
      {
        /**
         * 字典名称: {
         *    name: 字典名称,
         *    data: 字典数据(数组),
         *    update: 更新时间
         * },
         * ....
         */
      },
  },
  getters: {
    getDictState: (state: any) => {
      return state;
    },
    getDictSource: (state: any) => {
      // 遍历对象
      const trueDict: any = {};
      for (const key in state.dictsMap) {
        trueDict[key] = state.dictsMap[key].data;
      }
      return trueDict;
    },
  },
  mutations: {
    // 设置字典
    setDicts(state: any, minDicts: any) {
      // 将 minDicts 里的数据覆盖到 state.dicts 里
      for (const key in minDicts) {
        if (!state.dictsMap[key]) state.dictsMap[key] = [];
        // state.dictsMap[key] = minDicts[key];
        state.dictsMap[key] = {
          name: minDicts[key].name,
          data: minDicts[key],
          update: new Date().getTime(),
        };
        uni.setStorageSync("__APP__DICTS", state.dictsMap);
      }
      // console.log(state.dictsMap);
    },
  },
};
export default dicts;
